import axios from 'axios';
import { showMessage } from './status';
// import { getToken } from '@/utils/auth';
// import { TokenPrefix } from '@/utils/auth';
import { ADMIN_USER_TOKEN, USER_TOKEN, BASE_URL } from '@/store/constants';

const service = axios.create({
  // baseURL: import.meta.env.BASE_URL + '',
  baseURL: BASE_URL + '',
  timeout: 15000,
});

// axios实例拦截请求
service.interceptors.request.use(
    (config) => {
      config.headers.ADMINTOKEN = localStorage.getItem(ADMIN_USER_TOKEN);
      config.headers.TOKEN = localStorage.getItem(USER_TOKEN);
      return config;
    },
    (error) => {
      return Promise.reject(error);
    },
);

// axios实例拦截响应
service.interceptors.response.use(
    (response) => {
      if (response.status === 200) {
          if(response.data.code === 0 || response.data.code === 200) {
              // 新增条件检查，仅当响应数据中存在特定于评论的标识时调用setInfo
              if (response.data.action === 'fetchComment' || response.config.url.includes('comment')) {
                  if (response.config.method !== 'delete') {
                      setInfo(response);
                  }
              }

          return response;
        } else {
          return Promise.reject(response.data);
        }
      } else {
        return Promise.reject(response.data);
      }
    },
    // 请求失败
    (error) => {
      console.log(error.response.status);
      if (error.response.status === 404) {
        // todo
      } else if (error.response.status === 403) {
        // todo
      }
      return Promise.reject(error);
    },
);

const setInfo = (response) => {
    if (response.data.data != null && response.data.data.list != null) {

        for (let i = 0; i < response.data.data.list.length; i++) {
            //
            // // 将时间戳字段转换为可读日期时间
            // if (response.data.data.list[i].createTime) {
            //     const createTime = Number(response.data.list[i].createTime);
            //     if (!isNaN(createTime)) {
            //         const date = new Date(createTime);
            //         if (!isNaN(date.getTime())) {
            //             response.data.data.list[i].createTime = date.toLocaleString();
            //         } else {
            //             console.warn('Invalid timestamp:', createTime);
            //         }
            //     } else {
            //         console.warn('Invalid timestamp format:', response.data.list[i].createTime);
            //     }
            // }
            if (response.data.data.list[i].commentTime){
                    const commentTime = Number(response.data.data.list[i].commentTime);
                if (!isNaN(commentTime)) {
                    const date = new Date(commentTime);
                    if (!isNaN(date.getTime())) {
                        response.data.data.list[i].commentTime = date.toLocaleString();
                    } else {
                        console.warn('Invalid timestamp:', commentTime);
                    }
                } else {
                    console.warn('Invalid timestamp format:', response.data.data.list[i].commentTime);
                }
            }
        }

    }
}
const request = (config) => {
  return new Promise((resolve, reject) => {
    service.request(config).then((res) => {
      const data = res.data;
      resolve(data);
    }).catch(err => {
      reject(err);
    });
  });
};

export function get(config) {
  return request({ ...config, method: 'GET' });
}

export function post(config) {
  return request({ ...config, method: 'POST' });
}
// DELETE 请求封装
export const del = async ({ url, params = {}, headers = {} }) => {
    try {
        const response = await service.delete(url, { params, headers });
        return response.data;
    } catch (error) {
        console.error(error);
        throw error;
    }
};

export default request;
